//
//  AddNoteViewCtrl.m
//  DogeLegs
//
//  Created by 宋华 on 2017/8/19.
//  Copyright © 2017年 宋华. All rights reserved.
//

#import "AddNoteViewCtrl.h"
#import "NoteItemViews.h"
#import "QBImagePickerController.h"
#import "CameraManager.h"
#import "ChooseCateoryViewCtrl.h"
#import "LocationManager.h"
#import "NoteDraftManager.h"
#import "ImageMode.h"
#import "LocationCateoryCell.h"
#import "LocationCateoryView.h"

#define kImgActionSheetTag 100
#define kDraftActionSheetTag 101

@interface AddNoteViewCtrl () <UITextFieldDelegate,UITextViewDelegate,LCActionSheetDelegate,UIImagePickerControllerDelegate,QBImagePickerControllerDelegate,UINavigationControllerDelegate>{

}

@property (weak, nonatomic) IBOutlet UIScrollView *mainScrollview;

@property (weak, nonatomic) IBOutlet UITextField *titleField;

@property (weak, nonatomic) IBOutlet UITextView *contentTextView;

@property (weak, nonatomic) IBOutlet NoteItemViews *noteItemVIews;


@property (weak, nonatomic) IBOutlet UITextField *priceTextFiled;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bgCenterSize;

@property (weak, nonatomic) IBOutlet LocationCateoryView *locationCateoryView;

@property (weak, nonatomic) IBOutlet UIView *bottomLineview;

@property (weak, nonatomic) IBOutlet UIButton *addNoteBtn;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *noteItemsHeight;

@property (nonatomic,assign)CGFloat iP5PriceOffsetY;

- (IBAction)addNote:(id)sender;

@property (nonatomic,strong)NSMutableArray *uploadimages;//保存3x最大原图用来上传用

@property (nonatomic,strong)NSMutableArray *disPlayimages;//展示用的小图

@property (nonatomic,strong)NoteCateoryMode *chooseCateory;

@end

@implementation AddNoteViewCtrl

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"post";
    
    [self layoutAllSubviews];
    
    [NSNotificationCenter addUserAddressNF:self action:@selector(getUserAddressDone:)];
    [[LocationManager sharedInstance] startLocation];
    
    //如果有草稿，展示草稿
    [self displayDraft];
    
     // Do any additional setup after loading the view from its nib.
}


- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];

}

- (void)awakeFromNib {
    [super awakeFromNib];
    
    

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -界面
- (void)layoutAllSubviews {
    WeakSelf(ws);
    setCornerRadius(self.addNoteBtn, 5.0f);
    [self layoutNoteItemViews];
    [self navBarLeftButtonImage:@"back"];
    self.contentTextView.textContainerInset = UIEdgeInsetsMake(0, 0, 0, 0);//设置页边距
    UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(registFirstResponse:)];
    [self.mainScrollview addGestureRecognizer:tapGes];
    
    self.locationCateoryView.choCateoryBlock = ^(PostCellType type) {
        if (type == PostCellType_cateory) {
            [ws choosecateory:nil];
        }
    };
}


- (void)layoutNoteItemViews {
    [self.noteItemVIews reloadItems:self.disPlayimages topLeftPoint:CGPointMake(0, 0) isAddNote:YES];
    WeakSelf(ws);
    self.noteItemVIews.addPicBlock = ^{
        NSLog(@"addPicBlock");
        [ws.view endEditing:YES];
        LCActionSheet *actionSheet = [[LCActionSheet alloc] initWithTitle:nil buttonTitles:@[@"拍照",@"从相册选取"] redButtonIndex:0 delegate:ws];
        actionSheet.tag = kImgActionSheetTag;

        [actionSheet show];
    };
    self.noteItemVIews.deletePicBlock = ^(NSInteger index) {
        NSLog(@"deltePicBlock is %ld",(long)index);
        [ws delteImage:index];
    };

}

- (void)reloadNoteItemViews {
    [self.noteItemVIews reloadItems:self.disPlayimages topLeftPoint:CGPointMake(0, 0) isAddNote:YES];
    self.noteItemsHeight.constant = self.noteItemVIews.totalHeight;
    self.bgCenterSize.constant = self.noteItemVIews.totalHeight - 60;
}


- (void)displayDraft {
     NoteDraftMode *drfatMode =  [[NoteDraftManager sharedInstance] getDraftModeFromCache];
    if (drfatMode) {
        self.priceTextFiled.text = drfatMode.price;
        self.titleField.text = drfatMode.noteTitle;
        self.contentTextView.text = drfatMode.noteContent;
        self.chooseCateory = drfatMode.notecateory;
        for (NSInteger i = 0; i < drfatMode.uploadImages.count; i++) {
            NSString *path = drfatMode.uploadImages[i];
            UIImage *image = [UIImage imageWithContentsOfFile:path];
            [self.uploadimages addObject:image];
        }
        
        for (NSInteger i = 0; i < drfatMode.displayImages.count; i++) {
            NSString *path = drfatMode.displayImages[i];
            UIImage *image = [UIImage imageWithContentsOfFile:path];
            [self.disPlayimages addObject:[ImageMode localImageMode:image]];
        }
        [self reloadNoteItemViews];
    }
    self.locationCateoryView.cateory = chekCateory(self.chooseCateory.cateoryName) ;
}

#pragma mark delegate : UITextFieldDelegate
- (BOOL)strisVailded:(NSString *)_text {
    NSArray *strArrs = [_text componentsSeparatedByString:@"."];
    NSString *intergerStr = [strArrs getObjectAtIndex:0];
    NSString *floatStr = [strArrs getObjectAtIndex:1];
    
    BOOL isVailed = isPureNumandCharacters(_text);
    
    return isVailed && (intergerStr.length <= kPriceMaxIntegerNum) &&(floatStr.length <= kPriceMaxFloatNum) && (strArrs.count <=2);//防止输入更多.;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (textField == self.priceTextFiled) {
        NSString *str = [textField.text stringByReplacingCharactersInRange:range withString:string];
        if (![self strisVailded:str]) {
            return NO;
        }
        textField.text = str;
    } else if (textField == self.titleField) {
        return YES;
    }
    return NO;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if (textField == self.priceTextFiled) {
            [self.mainScrollview setContentOffset:CGPointMake(0, self.iP5PriceOffsetY) animated:YES];
    }
    
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField endEditing:YES];
    return YES;
}


#pragma mark delegate :IBActionSheetDelegate
- (void)actionSheet:(LCActionSheet *)actionSheet didClickedButtonAtIndex:(NSInteger)buttonIndex {
    if (actionSheet.tag == kImgActionSheetTag) {
        if (buttonIndex == 0) {
            [self presentCameraController];
        } else if (buttonIndex == 1) {
            [self presentImagePickerController];
        }
    } else if (actionSheet.tag == kDraftActionSheetTag) {
        NSLog(@"buttonIndex is %ld",(long)buttonIndex);
        if (buttonIndex == 0) {
            [[NoteDraftManager sharedInstance] saveDraftMode:self.priceTextFiled.text noteTitle:self.titleField.text noteContent:self.contentTextView.text noteCateory:self.chooseCateory disImgs:self.disPlayimages uplImgs:self.uploadimages];
            [self.navigationController popViewControllerAnimated:YES];
        } else if (buttonIndex == 1) {
            [[NoteDraftManager sharedInstance] cleanDraftMode];
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    
}

- (void)presentCameraController {
    WeakSelf(ws);
    [CameraManager authorizationStatusForCamera:^(BOOL granted) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            UIImagePickerController *imgPicker=[[UIImagePickerController alloc] init];
            imgPicker.delegate= ws;
            imgPicker.sourceType=UIImagePickerControllerSourceTypeCamera;
            [ws.navigationController presentViewController:imgPicker animated:YES completion:^{
                
            }];
        }
    }];
}

- (void)presentImagePickerController {
    ALAuthorizationStatus status = [CameraManager authorizationStatusForPhotoLibary];
    if (status == ALAuthorizationStatusAuthorized || status == ALAuthorizationStatusNotDetermined) {
        
        QBImagePickerController *imagePickerController = [[QBImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.maximumNumberOfSelection = kNotePictureMaxNum - self.disPlayimages.count;
        imagePickerController.showsNumberOfSelectedAssets = YES;
        imagePickerController.allowsMultipleSelection = YES;
        [self presentViewController:imagePickerController animated:YES completion:NULL];
      
    }
}

#pragma mark - UIImagePickerControllerDelegate & QBImagePickerControllerDelegate

- (void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didFinishPickingAssets:(NSArray *)assets {
    
    for (PHAsset *asset in assets) {
        @autoreleasepool {
            // 是否要原图,相册里图片也就是屏幕的scale倍,完全合理范围,不需要压缩,有可能它们是照相的比较大
            CGSize size = maxSize(CGSizeMake(asset.pixelWidth, asset.pixelHeight));
            PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
            // 同步获得图片, 只会返回1张图片
            options.synchronous = YES;
            options.resizeMode = PHImageRequestOptionsResizeModeExact;
            
            // 从asset中获得图片
            WeakSelf(ws);
            [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:size contentMode:PHImageContentModeAspectFit options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
//                NSData *data = UIImageJPEGRepresentation(result,1.0f);
                NSLog(@"scale is %f",result.scale);
                [ws dealOriginImage:result];
                NSLog(@"%@", result);
            }];
        }
    
    }
    
    [self dismissViewControllerAnimated:YES completion:NULL];
    
}

- (void)qb_imagePickerControllerDidCancel:(QBImagePickerController *)imagePickerController {
    [self dismissViewControllerAnimated:YES completion:NULL];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    @autoreleasepool {
        // info 包含了图片的数据
        UIImage *originalImage = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        
        [self dealOriginImage:originalImage];
    }
   
    //图片上传和其他资料一起用form表单上传
    [self.navigationController dismissViewControllerAnimated:YES completion:^{
        //
        
    }];
}

#pragma mark  -图片处理
- (void)dealOriginImage:(UIImage *)originalImage {
    @autoreleasepool {
        UIImage *compressImage = scaleImageToMaxSize(originalImage);
        //进一步压缩1.0f~0.1f的压缩比好像图片并没有看起来模糊，奇怪，图片成像原理不太清楚
        NSData *data = UIImageJPEGRepresentation(compressImage, 0.2f);
        UIImage *image = [UIImage imageWithData:data];
        
        UIImage *displayImage = cutCenterImageSize(CGSizeMake(ItemsWidth,ItemsWidth),image);
        
        [self addImage:image displayImage:displayImage];
    }
}


#pragma mark - private
- (BOOL)isTitleVail {
    return self.titleField.text.length >0;
}

- (BOOL)isContentVail {
    return self.contentTextView.text.length >0;
}

- (BOOL)isCateoryVail {
    return self.chooseCateory != nil;
}

- (BOOL)isRequireParamsVail {
    if (!self.isTitleVail) {
        [SVProgressHUD showErrorWithStatus:@"Please input title"];
        return NO;

    } else if (!self.isContentVail) {
        [SVProgressHUD showErrorWithStatus:@"Please input Content"];

        return NO;

    } else if (!self.isCateoryVail) {
        [SVProgressHUD showErrorWithStatus:@"Please choose a cateory"];
        return NO;
    }
    return YES;
}

- (BOOL)isAnyParamVail {
    return self.isTitleVail || self.isContentVail || self.isCateoryVail || self.uploadimages.count > 0 || self.priceTextFiled.text.length > 0 || (self.chooseCateory != nil);
}


#pragma mark - action事件
- (IBAction)choosecateory:(id)sender {
    WeakSelf(ws);
    ChooseCateoryViewCtrl *chosCtrl = [[ChooseCateoryViewCtrl alloc] initWithNibName:@"ChooseCateoryViewCtrl" bundle:nil];
    chosCtrl.chsDoneBlock = ^(NoteCateoryMode *catMode) {
        ws.chooseCateory = catMode;
        self.locationCateoryView.cateory = chekCateory(catMode.cateoryName) ;
    };
    [self.navigationController pushViewController:chosCtrl animated:YES];
}
- (IBAction)addNote:(id)sender {
    if ([self isRequireParamsVail]) {//必要的参数都填写了
        NSLog(@"addNoteDone");
    }
    
}

- (void)leftButtonclickEvent:(id)sender {
    if (self.isAnyParamVail) {
        LCActionSheet *actionSheet = [[LCActionSheet alloc] initWithTitle:@"Do you want to save this draft?" buttonTitles:@[@"SAVE",@"Dont Save"] redButtonIndex:0 delegate:self];
        actionSheet.tag = kDraftActionSheetTag;
        [actionSheet show];
    } else {//啥都没填就出去了
        [[NoteDraftManager sharedInstance] cleanDraftMode];
    }
}

- (void)registFirstResponse:(UIGestureRecognizer *)_ges {
    [self.view endEditing:YES];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

#pragma mark - 通知事件
- (void)getUserAddressDone:(NSNotification *)not {
    NSDictionary *userInfo = not.userInfo;
    NSString *address = userInfo[UserAddress];
    self.locationCateoryView.address = address;
}

#pragma mark - getter 
- (NSMutableArray *)uploadimages {
    if (_uploadimages == nil) {
        _uploadimages = [NSMutableArray array];
    }
    return _uploadimages;
}

- (NSMutableArray *)disPlayimages {
    if (_disPlayimages == nil) {
        _disPlayimages = [NSMutableArray array];
    }
    return _disPlayimages;
}


- (void)addImage:(UIImage *)uploadimage displayImage:(UIImage *)displayImage {
    [self.uploadimages addObject:uploadimage];
    [self.disPlayimages addObject:[ImageMode localImageMode:displayImage]];
    [self reloadNoteItemViews];
}

- (void)delteImage:(NSInteger)index {
    [self.uploadimages removeObjectAtIndex:index];
    [self.disPlayimages removeObjectAtIndex:index];
    [self reloadNoteItemViews];
}


- (CGFloat)iP5PriceOffsetY {
//    NSInteger rowCount = (self.images.count + 1 - 1)/kColumn + 1;
//    CGFloat seHeight = rowCount *ItemsWidth + (rowCount -1) *kItem_Y_space;
    CGFloat offset = 0;
    CGFloat botLine = self.bottomLineview.bottom;
    CGFloat maxY = kScreenHeight - kNavAndStatusBarHeight - kNumkeybordHeight;//price不被遮住最大的Y坐标
    if (botLine < maxY) {
        offset = 0;
    } else {
        offset = botLine - maxY;
    }
    return offset;
}

@end
